<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<title>角色管理</title>
		<script src="../js/global.js" type="text/javascript" charset="utf-8"></script>
		<script type="text/html" id="toolbarDemo">
			<div class="layui-btn-container">
				<button type="button" class="layui-btn layui-btn-sm" lay-event="add">
  					<i class="layui-icon">&#xe608;</i>添加角色
				</button>
			</div>
		</script>
		<script type="text/html" id="barDemo">
			<a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="setModule"><i class="layui-icon">&#xe620;</i>设置权限</a>
			<a class="layui-btn layui-btn-xs" lay-event="edit"><i class="layui-icon">&#xe642;</i>编辑</a>
			<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del"><i class="layui-icon">&#xe640;</i>删除</a>
		</script>

		<script>
			layui.config({
				version: '1560414887305' //为了更新 js 缓存，可忽略
			});

			var addIndex, editIndex, setIndex; //弹出的添加、修改、设置层
			var cur_roleId; //正在编辑的角色id			
			var arr = []; //声明数组，用于保存选中的tree节点的Id

			layui.use(['laypage', 'layer', 'table', 'element', 'form', 'tree'], function() {
				laypage = layui.laypage //分页
					, layer = layui.layer //弹层
					, table = layui.table //表格
					, element = layui.element //元素操作
					, form = layui.form //表单
					, tree = layui.tree; //树

				//渲染数据表格
				table.render({
					elem: '#roleTable',
					toolbar: '#toolbarDemo',
					height: 550,
					url: globalData.server + 'roles/GetRolesLayUI', //数据接口
					method: 'post',
					where: {
						'token': globalData.token
						//,'limit': 10
						//,'page': 1
					},
					title: '角色列表',
					page: true, //开启分页
					cols: [
						[ //表头
							{
								type: 'numbers',
								title: '序号',
								width: 80,
								fixed: 'left'
							}, {
								field: 'Id',
								title: 'ID',
								width: 150,
								hide: true,
								fixed: 'left'
							}, {
								field: 'name',
								title: '角色名',
								width: 250
							}, {
								fixed: 'right',
								title: '操作',
								width: 250,
								align: 'center',
								toolbar: '#barDemo'
							}
						]
					],
					id: "testReload", //表格的ID标识
					done: function(res, curr, count) {
						loadCurr = false;
					}
				});

				var $ = layui.$,
					active = { //用于定义重新加载表格数据的方法
						reload: function() {
							var demoReload = $('#demoReload');
							if(loadCurr) {
								table.reload('testReload', {
									where: {
										'token': globalData.token
									}
								});
							} else {
								table.reload('testReload', {
									where: {
										'token': globalData.token
									},
									page: {
										curr: 1 //重新从第 1 页开始
									}
								});
							}
						}
					};

				//给添加和修改表单中的token赋值
				$("#hfTokenAdd").val(globalData.token);
				$("#hfTokenEdit").val(globalData.token);

				//监听数据行工具栏按钮事件
				table.on('tool(test)', function(obj) { //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
					var data = obj.data; //获得当前行数据
					var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
					var tr = obj.tr; //获得当前行 tr 的DOM对象

					if(layEvent === 'setModule') { //设置模块
						arr = [];
						$.post(globalData.server + "roles/GetModulesByRoleIdLayUI", {
							token: globalData.token,
							rolesIds: data.id
						}, function(r) {
							tree.render({
								elem: '#rightTree',
								data: r,
								id: 'roleTreeId',
								showCheckbox: true
							})
							cur_roleId = data.id;
						}, "json");
						//打开设置权限窗口
						setIndex = layer.open({
							type: 1,
							content: $('#diaSetRight'),
							title: "正在设置角色[" + data.name + "]的权限模块",
							area: ['300px', '400px']
						});
					} else if(layEvent === 'del') { //删除
						layer.confirm('确定要删除角色[' + data.name + ']的信息吗', function(index) {
							$.post(globalData.server + "roles/DeleteRole", {
								id: data.id,
								token: globalData.token
							}, function(r) {
								if(r) {
									layer.msg('删除成功', {
										icon: 1,
										time: 1000
									}, function() {
										//重新渲染表格数据
										obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
										layer.close(index);
									});
								} else {
									layer.msg('删除失败', {
										icon: 1,
										time: 2000
									});
								}
							}, "json");
						});
					} else if(layEvent === 'edit') { //编辑
						//给修改表单元素赋值
						$("#txtRoleId").val(data.id);
						$("#editName").val(data.name);
						//打开修改层
						editIndex = layer.open({
							type: 1,
							content: $('#edit'),
							title: "您正在修改角色[" + data.name + "]的信息",
							area: ['400px', '300px']
						});
					}
				});

				//表格头工具栏按钮事件
				table.on('toolbar(test)', function(obj) {
					var checkStatus = table.checkStatus(obj.config.id);
					switch(obj.event) {
						case 'add': //打开添加层
							addIndex = layer.open({
								type: 1,
								content: $('#add'),
								title: "您正在添加角色信息",
								area: ['400px', '300px']
							});
							break;
					};
				});

				//添加表单的保存事件
				form.on('submit(addRole)', function(data) {
					$.post(globalData.server + "roles/CreateRole", $("#formAddRole").serialize(), function(r) {
						if(r) {
							layer.msg('添加成功', {
								icon: 1,
								time: 1000
							}, function() {
								layer.close(addIndex); //关闭添加弹出层
								active["reload"].call(null); //重新加载表格数据						  	
							});
						} else {
							layer.msg('添加失败', {
								icon: 1,
								time: 2000
							});
						}
					}, "json");
					return false;
				});

				//修改表单的保存事件
				form.on('submit(editRole)', function(data) {
					$.post(globalData.server + "roles/UpdateRole", $("#formEditRole").serialize(), function(r) {
						if(r) {
							layer.msg('修改成功', {
								icon: 1,
								time: 1000
							}, function() {
								layer.close(editIndex); //关闭修改弹出层
								loadCurr = true;
								active["reload"].call(null); //重新加载表格数据
							});
						} else {
							layer.msg('修改失败', {
								icon: 1,
								time: 2000
							});
						}
					}, "json");
					return false;

				});

				//给角色设置权限
				$("#setRole").click(function() {
					var nodes = tree.getChecked('roleTreeId');
					//字符串拼接基本功，要求手熟
					for(var i = 0; i < nodes.length; i++) {
						getChildenId(nodes[i]); //调用递归的方法来获取所有选中节点的Id
					}
					//调用远程接口保存设置
					$.post(globalData.server + "roles/SetSysRights", {
						parentIds: arr.join(","),
						rId: cur_roleId,
						token: globalData.token
					}, function(r) {
						if(r) {
							layer.msg('保存权限成功！', {
								icon: 1,
								time: 1000
							}, function() {
								layer.close(setIndex); //关闭修改弹出层
								window.top.getMenu();
							});
						} else {
							layer.msg('保存权限失败！', {
								icon: 2,
								time: 1000
							})
						}
					}, "json");
				});

				//var active={del:3,reload:1,load:2};
				$('.demoTable .layui-btn').on('click', function() {
					var type = $(this).data('type');
					active[type] ? active[type].call(this) : '';
				});

			});
			var arr = [];
			//递归获取选中节点的Id
			function getChildenId(node) {
				if(node != null) {
					arr.push(node.id);
					for(var i = 0; node.children != null && i < node.children.length; i++) {
						getChildenId(node.children[i]);
					}
				}
			}
		</script>

		<style>
			#tabEdit {
				margin: 30px auto;
			}
			
			#tabEdit td {
				line-height: 35px;
			}
		</style>
	</head>

	<body>
		<div style="margin: 10px auto; width: 600px; height: 620px;">
			<table id="roleTable" lay-filter="test" class="layui-hide" lay-data="{id: 'idTest'}"></table>
		</div>
		<!--添加-->
		<div id="add" style="display: none;" title="您正在添加角色信息" style="width:400px;height:250px;" data-options="iconCls: 'icon-save',resizable:true,modal:true,closed:true">
			<form id="formAddRole" method="post" action="" style="margin-top:20px;" class="layui-form">
				<input id="hfTokenAdd" name="token" type="hidden" />
				<div class="layui-form-item">
					<label class="layui-form-label">角色名:</label>
					<div class="layui-input-block">
						<input id="addName" type="text" name="name" placeholder="请输入角色名" autocomplete="off" class="layui-input" lay-verify="required" style="width: 180px;">
					</div>
				</div>
				<div class="layui-form-item">
					<div class="layui-input-block">
						<button class="layui-btn" id="btnAddSave" lay-submit="" lay-filter="addRole"><i class="layui-icon">&#xe605;</i>保存</button>
						<button type="reset" class="layui-btn layui-btn-primary"><i class="layui-icon">&#x1006;</i>重置</button>
					</div>
				</div>
			</form>
		</div>
		<!--编辑-->
		<div id="edit" style="display: none;" title="编辑角色信息" style="width:400px;height:200px;" data-options="iconCls: 'icon-save',resizable:true,modal:true,closed:true">
			<form id="formEditRole" method="post" action="" style="margin-top:20px;" class="layui-form">
				<input id="txtRoleId" name="id" type="hidden" />
				<input id="hfTokenEdit" name="token" type="hidden" />
				<div class="layui-form-item">
					<label class="layui-form-label">角色名:</label>
					<div class="layui-input-block">
						<input id="editName" type="text" name="name" autocomplete="off" class="layui-input" lay-verify="required" style="width: 180px;">
					</div>
				</div>
				<div class="layui-form-item">
					<div class="layui-input-block">
						<button class="layui-btn" id="btnEditSave" lay-submit="" lay-filter="editRole"><i class="layui-icon">&#xe605;</i>保存</button>
						<button type="reset" class="layui-btn layui-btn-primary"><i class="layui-icon">&#x1006;</i>重置</button>
					</div>
				</div>
			</form>
		</div>
		<!--设置权限-->
		<div id="diaSetRight" style="display: none;" title="设置权限" style="width:300px;height:600px; margin: 10px auto;">
			<table id="tabEdit">
				<tr>
					<td>
						<div id="rightTree"></div>
					</td>
				</tr>
				<tr>
					<td style="text-align: center; padding: 10px;">
						<a id="setRole" href="#" class="layui-btn"><i class="layui-icon">&#xe605;</i>保存设置</a>
					</td>
				</tr>
			</table>

		</div>

	</body>

</html>